<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { SwapOutlined } from '@ant-design/icons-vue';
import { SimpleScrollbar } from '@sa/materials';
import { useRouterPush } from '@/hooks/common/router';
import { getProjectListApi, getUnitListApi } from '@/service/api/businessApi';
import { OverviewDevice } from '@/service/api/dashboard';
import { useProjectStore } from '@/store/modules/project';
import { useEcharts } from '@/hooks/common/echarts';
import { ProvinceProject } from '@/service/api/bigScreen';
import { chinaJson } from '@/enum/china';
import { useRouteStore } from '@/store/modules/route';
import { useAuthStore } from '@/store/modules/auth';
import cityJson from '../systemManage/projectManage/staticData/city';
const routeStore = useRouteStore();
const authStore = useAuthStore();
const { routerPush } = useRouterPush();
const projectStore = useProjectStore();

const projectList: any = ref([]);

const getProjectList = () => {
  getProjectListApi({
    pageNo: 1,
    pageSize: 1000,
    orgId: authStore.userInfo?.orgId
  }).then(res => {
    projectList.value = res.data?.data;
    projectList.value.forEach((item: any) => {
      item.key = item.id;
    });
  });
};

const equipmentAllNum: any = ref({
  gatewayNum: 0,
  hostNum: 0,
  deviceNum: 0,
  monitorNum: 0
});

// 获取设备数量
const getOverviewDevice = () => {
  OverviewDevice({ orgId: projectStore.currentProject?.orgId }).then(res => {
    equipmentAllNum.value.hostNum = res.data?.hostNum;
    equipmentAllNum.value.deviceNum = res.data?.deviceNum;
    equipmentAllNum.value.monitorNum = res.data?.monitorNum;
    equipmentAllNum.value.gatewayNum = res.data?.gatewayNum;
  });
};

// 获取天气数据
const city = ref('厦门市');
const weatherData: any = ref({
  today: {},
  nextDay: {},
  lastDay: {}
});

// 返回天气图标
const weatherIcon = (icon: any) => {
  if (!icon) return;
  let newIcon = icon;
  if (newIcon.includes('雨') && newIcon !== '雷阵雨') {
    newIcon = '雨';
  }
  if (newIcon.includes('沙')) {
    newIcon = '沙尘';
  }
  return `/src/assets/imgs/weather/${newIcon}.png`;
};

const getWetherInfo = async () => {
  try {
    // 天气情况
    // https://lbs.amap.com/api/webservice/guide/tools/weather-code
    // 行政区域表
    // https://blog.csdn.net/CrazyApes/article/details/128957238
    navigator.geolocation.getCurrentPosition(
      async position => {
        const { latitude, longitude } = position.coords;
        const cityResponse = await fetch(
          `https://restapi.amap.com/v3/geocode/regeo?key=a3f91dbc1c2b8349f7494ca374282760&location=${longitude},${latitude}&extensions=base`
        );
        const cityData = await cityResponse.json();
        const adcode = cityData.regeocode.addressComponent.adcode;
        switchCityValue.value = splitRegionCode(adcode);
        city.value = cityData.regeocode.addressComponent.city;
        const response = await fetch(
          `https://restapi.amap.com/v3/weather/weatherInfo?key=a3f91dbc1c2b8349f7494ca374282760&city=${adcode}&extensions=all`
        );
        const data = await response.json();

        weatherData.value.today = data.forecasts[0].casts[0];
        weatherData.value.nextDay = data.forecasts[0].casts[1];
        weatherData.value.lastDay = data.forecasts[0].casts[2];
      },
      (error: any) => {
        // 获取定位失败, 直接切换厦门
        console.log(error);
        getWetherInfoByAdcode(350213);
      },
      {
        timeout: 2000
      }
    );
  } catch (error) {
    console.error('Error fetching weather data:', error);
  }
};

const getWetherInfoByAdcode = async (code: any) => {
  try {
    const adcode = code ?? switchCityValue.value[2];
    const response = await fetch(
      `https://restapi.amap.com/v3/weather/weatherInfo?key=a3f91dbc1c2b8349f7494ca374282760&city=${adcode}&extensions=all`
    );
    const data = await response.json();
    const cityResponse = await fetch(
      `https://restapi.amap.com/v3/geocode/geo?key=a3f91dbc1c2b8349f7494ca374282760&address=${data.forecasts[0].city}&city=${adcode}&extensions=all`
    );
    const cityShowData = await cityResponse.json();
    city.value = cityShowData.geocodes[0].city;
    weatherData.value.today = data.forecasts[0].casts[0];
    weatherData.value.nextDay = data.forecasts[0].casts[1];
    weatherData.value.lastDay = data.forecasts[0].casts[2];
  } catch (error) {
    console.error('Error fetching weather data:', error);
  }
};

const changeProject = (val: any) => {
  const currentProject = projectList.value.find((item: any) => item.id === val.key);
  projectStore.changeCurrentProject(currentProject);
  routerPush(`/breedAquatics?projectId=${currentProject.id}`);
};

const { domRef, updateOptions } = useEcharts(() => ({
  title: {
    text: '',
    subtext: '',
    x: 'center'
  },
  legend: {
    show: false,
    orient: 'horizontal', // 图例的排列方向
    x: 'left',
    data: ['']
  },
  tooltip: {
    show: true,
    trigger: 'item',
    formatter(params: any) {
      if (params.value.length > 1) {
        return `&nbsp;&nbsp;${params.name}&nbsp;&nbsp;&nbsp;项目数: ${params.value[2]}&nbsp;&nbsp;`;
      }
      return `&nbsp;&nbsp;${params.name}&nbsp;&nbsp;&nbsp;项目数: ${params.value}&nbsp;&nbsp;`;
    }
  },
  visualMap: {
    show: false,
    x: 'left',
    y: 'center',
    splitList: [
      { start: 8000, end: 12000 },
      { start: 5000, end: 8000 },
      { start: 4000, end: 5000 },
      { start: 3500, end: 4000 },
      { start: 2500, end: 3500 },
      { start: 800, end: 2500 },
      { start: 50, end: 800 }
    ],
    text: ['高', '低'],
    color: ['#93CDE1', '#6EC2EE', '#2961AD']
  },
  toolbox: {
    show: false,
    orient: 'vertical',
    x: 'right',
    y: 'center',
    feature: {
      mark: { show: true },
      dataView: { show: true, readOnly: false },
      restore: { show: true },
      saveAsImage: { show: true }
    }
  },
  roamController: {
    show: true,
    x: 'right',
    mapTypeControl: {
      china: true
    }
  },
  series: [
    {
      name: '人口数量',
      type: 'map',
      map: 'china',
      roam: false,
      top: '3%',
      data: [],
      itemStyle: {
        borderWidth: 1, // 设置边界线宽度
        borderColor: '#888' // 设置边界线颜色
      }
    }
  ]
}));

const goto = (route: string) => {
  sessionStorage.setItem('menusKey', 'system');
  routeStore.resetStore();
  setTimeout(() => {
    routerPush(route);
  }, 100);
};

const seriesList: any = ref();
const getProvinceProject = () => {
  ProvinceProject().then(Res => {
    const _data = Res.data;
    _data.forEach(item => {
      chinaJson.forEach((it, idx) => {
        if (item.provinceCode == it.code) {
          chinaJson[idx].value = item.projectNum;
          chinaJson[idx].itemStyle = { areaColor: 'red' };
        }
      });
    });
    updateEchartOptions(chinaJson);
  });
};
const updateEchartOptions = chinaJson => {
  updateOptions(opts => {
    opts.series[0].data = chinaJson;
    return opts;
  });
};
/* 切换城市相关逻辑 */
const switchCityVisible = ref(false);
const switchCityValue = ref();
const switchCityChange = () => {
  getWetherInfoByAdcode();
  switchCityVisible.value = false;
};
/* 切换城市相关逻辑 */

/* 简洁相关代码 */
const unitDetail = ref();
const getUnitInfo = () => {
  getUnitListApi({
    id: authStore.userInfo?.orgId
  }).then(res => {
    if (res.data.data.length > 0) {
      unitDetail.value = res.data.data[0];
    }
  });
};
/* 简洁相关代码 */

/* 工具类函数 */
const splitRegionCode = (code: string) => {
  // 转换为字符串以防输入的是数字
  const str = String(code);
  // 检查长度是否为6位（标准的地区代码长度）
  if (str.length !== 6) {
    throw new Error('地区代码必须是6位数字');
  }
  return [str.substring(0, 2), str.substring(0, 4), str];
};
/* 工具类函数 */

onMounted(() => {
  getProvinceProject();
  getWetherInfo();
  getProjectList();
  getOverviewDevice();
  getUnitInfo();
});
</script>

<template>
  <div class="page-wrapper">
    <div :class="projectList.length > 1 ? 'header' : 'header-no-text'">
      <div class="btn1" @click="goto('/systemmanage/projectmanage')">
        <span>系统管理</span>
      </div>
      <div v-if="projectList.length === 1" class="btn2" @click="changeProject(projectList[0])">
        <span>项目详情</span>
      </div>
      <ADropdown v-else overlay-class-name="heh-dropdown" style="position: relative">
        <div class="btn2">
          <span>项目列表</span>
        </div>
        <template #overlay>
          <AMenu @click="changeProject">
            <SimpleScrollbar class="menu-wrapper">
              <AMenuItem v-for="item in projectList" :key="item.id">
                {{ item.name }}
              </AMenuItem>
            </SimpleScrollbar>
          </AMenu>
        </template>
      </ADropdown>
    </div>

    <div class="right">
      <div class="right-top">
        <div class="top-top">项目总数</div>
        <div class="top-left">
          <span>{{ projectList.length }}</span>
        </div>
        <div class="top-right">
          <div>{{ unitDetail?.brief || '项目简介' }}</div>
          <div>
            {{
              unitDetail?.detail ||
              '采用先进的养殖技术和设备提高养殖产品的质量和安全性。这种模式不仅有助于提高渔业生产的这个整体效益，还有助于推动渔业产业的可持续发展。'
            }}
          </div>
        </div>
      </div>
      <div class="right-mid">
        <div class="bg-blue">
          <span>传感器</span>
          <span class="ml-50px">{{ equipmentAllNum.gatewayNum }}</span>
        </div>
        <div class="bg-yellow">
          <span>终端</span>
          <span class="ml-50px">{{ equipmentAllNum.hostNum }}</span>
        </div>
        <div class="bg-yellow">
          <span>控制器</span>
          <span class="ml-50px">{{ equipmentAllNum.deviceNum }}</span>
        </div>
        <div class="bg-blue">
          <span>监控</span>
          <span class="ml-50px">{{ equipmentAllNum.monitorNum }}</span>
        </div>
      </div>
      <div class="right-bottom">
        <div class="bottom-top">
          天气 - {{ city }}
          <ATooltip :mouse-enter-delay="0.5">
            <template #title>切换城市</template>
            <SwapOutlined style="cursor: pointer" @click="switchCityVisible = true" />
          </ATooltip>
        </div>
        <div class="tq-wrapper">
          <div class="tq-item">
            <div>
              <span>{{ weatherData.today?.date }}</span>
              <span>今日</span>
            </div>
            <img :src="weatherIcon(weatherData.today?.dayweather)" alt="" />
            <p>{{ weatherData.today?.wea }}</p>
            <span>{{ weatherData.today?.nighttemp_float }}~{{ weatherData.today?.daytemp_float }}°C</span>
          </div>
          <div class="tq-item">
            <div>
              <span>{{ weatherData.nextDay?.date }}</span>
              <span>明日</span>
            </div>
            <img :src="weatherIcon(weatherData.nextDay?.dayweather)" alt="" />
            <p>{{ weatherData.nextDay?.wea }}</p>
            <span>{{ weatherData.nextDay?.nighttemp_float }}~{{ weatherData.nextDay?.daytemp_float }}°C</span>
          </div>
          <div class="tq-item">
            <div>
              <span>{{ weatherData.lastDay?.date }}</span>
              <span>后天</span>
            </div>
            <img :src="weatherIcon(weatherData.lastDay?.dayweather)" alt="" />
            <p>{{ weatherData.lastDay?.wea }}</p>
            <span>{{ weatherData.lastDay?.nighttemp_float }}~{{ weatherData.lastDay?.daytemp_float }}°C</span>
          </div>
        </div>
      </div>
    </div>

    <div class="left">
      <div ref="domRef" class="h-360px overflow-hidden"></div>
    </div>
    <div style="display: none">
      <ASelect class="w-250px" @change="changeProject">
        <ASelectOption v-for="item in projectList" :key="item.id" :value="item.id">
          {{ item.name }}
        </ASelectOption>
      </ASelect>
      <div></div>
      <AButton @click="() => routerPush('/breedingmanage/devicemanage')">跳转到监测平台</AButton>
    </div>

    <!-- 切换城市的弹出框 -->
    <AModal v-model:open="switchCityVisible" :width="400" title="切换城市" @ok="switchCityChange">
      <div class="pb-20px pt-20px">
        <ACascader
          v-model:value="switchCityValue"
          class="w-full"
          :options="cityJson"
          :field-names="{ label: 'name', value: 'code', children: 'children' }"
          placeholder="请选择省市区"
        />
      </div>
    </AModal>
    <!-- 切换城市的弹出框 -->
  </div>
</template>

<style scoped lang="scss">
.page-wrapper {
  width: 100%;
  height: 100%;
  background: url('@/assets/imgs/index-bg.png') no-repeat center;
  background-size: 100% 100%;

  %common-header {
    background-size: 100% 100%;
    position: relative;
    height: 220px;

    .btn1 {
      background: url('@/assets/imgs/btn1.png') no-repeat center;
      position: absolute;
      left: 320px;
      top: 9px;
      color: #fff;
      width: 244px;
      height: 68px;
      text-align: center;
      line-height: 56px;
      font-size: 18px;
      cursor: pointer;

      span {
        margin-left: 20px;
      }
    }

    .btn2 {
      background: url('@/assets/imgs/btn2.png') no-repeat center;
      position: absolute;
      right: 320px;
      top: 9px;
      color: #fff;
      width: 244px;
      text-align: center;
      height: 68px;
      line-height: 56px;
      font-size: 18px;
      cursor: pointer;

      span {
        margin-right: 20px;
      }
    }
  }
  .header {
    @extend %common-header;
    background: url('@/assets/imgs/index_header_back.png') no-repeat center;
  }

  .header-no-text {
    @extend %common-header;
    background: url('@/assets/imgs/index_header_notitle.png') no-repeat center;

    .title {
      text-align: center;
      line-height: 60px;
      font-size: 20px;
      color: #fff;
      font-weight: bold;
      text-shadow: 0px 1px 6px rgba(119, 169, 255, 0.5);
      letter-spacing: 1px;
    }
  }

  .right {
    position: absolute;
    right: 36px;
    top: 90px;
    width: 550px;

    .right-top {
      background: url('@/assets/imgs/bg_xm.png') no-repeat center;
      background-size: 100% 100%;
      height: 300px;
      padding: 16px 26px;
      display: flex;
      flex-wrap: wrap;

      .top-left {
        background: url('@/assets/imgs/pic_ball.png') no-repeat center;
        background-size: 100% 100%;
        width: 220px;
        height: 190px;
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: center;

        span {
          margin-top: -40px;
          font-size: 30px;
          color: #c9feff;
          text-shadow: 0px 1px 5px rgba(119, 169, 255, 0.5);
        }
      }

      .top-right {
        width: 250px;
        margin-top: 20px;

        div:first-child {
          font-size: 20px;
          margin-bottom: 10px;
          color: #83fff1;
        }

        div {
          color: #c9feff;
        }
      }

      .top-top {
        width: 100%;
        font-family: SourceHanSansCN, SourceHanSansCN;
        font-weight: bold;
        font-size: 18px;
        color: #ffffff;
        line-height: 40px;
        letter-spacing: 1px;
        text-shadow: 0px 1px 5px rgba(119, 169, 255, 0.5);
        text-align: left;
        font-style: normal;
        display: flex;
        align-items: center;
        gap: 8px;

        &::before {
          content: '';
          display: inline-block;
          height: 20px;
          width: 4px;
          background: #7ed5ff;
          box-shadow: 0px 1px 5px rgba(119, 169, 255, 0.5);
        }
      }
    }

    .right-mid {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      margin-top: 20px;
      gap: 10px;
      color: #d7f5ff;
      font-size: 16px;

      .bg-blue {
        background: url('@/assets/imgs/blue_btn.png') no-repeat center;
        background-size: 100% 100%;
        height: 89px;
        width: 250px;
        display: flex;
        align-items: center;
        padding-left: 26px;
      }

      .bg-yellow {
        background: url('@/assets/imgs/yellow_btn.png') no-repeat center;
        background-size: 100% 100%;
        height: 89px;
        width: 250px;
        display: flex;
        align-items: center;
        padding-left: 26px;
      }
    }

    .right-bottom {
      background: url('@/assets/imgs/bg_tq.png') no-repeat center;
      background-size: 100% 100%;
      height: 290px;
      margin-top: 10px;
      padding: 12px 32px;

      .bottom-top {
        width: 100%;
        font-family: SourceHanSansCN, SourceHanSansCN;
        font-weight: bold;
        font-size: 18px;
        color: #ffffff;
        line-height: 40px;
        letter-spacing: 1px;
        text-shadow: 0px 1px 5px rgba(119, 169, 255, 0.5);
        text-align: left;
        font-style: normal;
        display: flex;
        align-items: center;
        gap: 8px;

        &::before {
          content: '';
          display: inline-block;
          height: 20px;
          width: 4px;
          background: #7ed5ff;
          box-shadow: 0px 1px 5px rgba(119, 169, 255, 0.5);
        }
      }

      .tq-wrapper {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: -10px;
        gap: 16px;

        .tq-item {
          background: url('@/assets/imgs/card_tq.png') no-repeat center;
          background-size: 100% 100%;
          width: 204px;
          height: 220px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          img {
            width: 80px;
            height: 82px;
          }

          div {
            display: flex;
            align-items: center;

            span {
              font-weight: 500;
              font-size: 16px;
              color: #ffffff;

              &:nth-child(2) {
                margin-left: 5px;
              }
            }
          }

          & > span,
          p {
            font-weight: 400;
            font-size: 16px;
            color: #ffffff;
          }
        }
      }
    }
  }

  .left {
    width: calc(100% - 550px);
    position: absolute;
    top: 140px;
    left: 0;

    div {
      height: 760px;
    }
  }
}

.heh-dropdown {
  .menu-wrapper {
    max-height: 240px;
  }

  .ant-dropdown-menu {
    background: #19296a !important;
    transform: translateY(-10px);
    height: 240px;

    :deep(.ant-dropdown-menu-item) {
      color: #a2deff !important;

      &:hover {
        background: rgba(255, 255, 255, 0.11);
      }
    }
  }

  :deep(.ant-dropdown) {
  }
}
</style>
